package com.tron.dobest.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 定时任务执行逻辑
 */
public class SchedulingRunnable implements Runnable {

    private  final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 任务id
     */
    private String id;

    /**
     * 调用类的类名
     */
    private String beanName;

    /**
     * 调用方法的方法名
     */
    private String methodName;

    /**
     * 调用方法的参数
     */
    private Object[] params;


    @Override
    public void run() {
        invokeMethod();
    }

    private void invokeMethod(){
        try {
            Object bean = TronUtils.getBean(beanName);
            Method method = null;
            if (null != params && params.length > 0) {
                Class<?>[] paramCls = new Class[params.length];
                for (int i = 0; i < params.length; i++) {
                    paramCls[i] = params[i].getClass();
                }
                method = bean.getClass().getDeclaredMethod(methodName, paramCls);
            } else {
                method = bean.getClass().getDeclaredMethod(methodName);
            }
            ReflectionUtils.makeAccessible(method);
            if (null != params && params.length > 0) {
                method.invoke(bean, params);
            } else {
                method.invoke(bean);
            }
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            log.info("定时任务执行失败，异常信息：{}",e.getMessage());
        }
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public void setParams(Object[] params) {
        this.params = params;
    }
}
